package com.example.blog.hander;

import com.alibaba.fastjson.JSON;
import com.example.blog.admin.service.LoginService;
import com.example.blog.dao.pojo.SysUser;
import com.example.blog.admin.service.TokenService;
import com.example.blog.utils.UserThreadLocal;
import com.example.blog.admin.vo.ErrorCode;
import com.example.blog.admin.vo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private LoginService loginService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * preHandle
     * 调用时间：Controller方法处理之前
     * 执行顺序：链式Intercepter情况下，Intercepter按照声明的顺序一个接一个执行
     * 若返回false，则中断执行，注意：不会进入afterCompletion
     *
     * postHandle
     * 调用前提：preHandle返回true
     * 调用时间：Controller方法处理完之后，DispatcherServlet进行视图的渲染之前，也就是说在这个方法中你可以对ModelAndView进行操作
     * 执行顺序：链式Intercepter情况下，Intercepter按照声明的顺序倒着执行。
     * 备注：postHandle虽然post打头，但post、get方法都能处理
     *
     * afterCompletion
     * 调用前提：preHandle返回true
     * 调用时间：DispatcherServlet进行视图的渲染之后
     * 多用于清理资源
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        /**
         * 1.需要判断，请求的接口路径是否为 HandlerMethod (Controller方法）
         * 2.判断 token是否为空， 若为空 未登录
         * 3.若不为空， 登录验证
         * 4.如果认证成功，放行即可
         */
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        String token = request.getHeader("Authorization");

        // 打印日志信息
        log.info("=================request start===========================");
        String requestURI = request.getRequestURI();
        log.info("request uri:{}",requestURI);
        log.info("request method:{}",request.getMethod());
        log.info("token:{}", token);
        log.info("=================request end===========================");

        if (token == null) {
            Result result = Result.fail(ErrorCode.NO_LOGIN.getCode(), "未登录");
            response.setContentType("application/json; charset = utf-8");
            response.getWriter().print(JSON.toJSONString(result));
            return false;
        }

        SysUser sysUser = tokenService.checkLogin(token);
        if (sysUser == null) {
            Result result = Result.fail(ErrorCode.NO_LOGIN.getCode(), "未登录");
            response.setContentType("application/json; charset = utf-8");
            response.getWriter().print(JSON.toJSONString(result));
            return false;
        }

        // 判断是否应该顶掉线（对比前端传回的 token 和 redis通过 <username, token>存入的 token是否相同）
        String account = sysUser.getAccount();
        if (account != null) {
            String newToken = redisTemplate.opsForValue().get(account);
            if (!token.equals(newToken)) {
                // 删除旧版本token
                redisTemplate.delete("TOKEN_"+ token);

                Result result = Result.fail(ErrorCode.LOGIN_REPLACE.getCode(), "用户在其他客户端登录");
                response.setContentType("application/json; charset = utf-8");
                response.getWriter().print(JSON.toJSONString(result));
                return false;
            }
        }

        // 登录成功
        // 我希望在 Controller 中直接获取用户的信息， 怎么获取？？
        //通过 ThreadLocal , 将数据存入到 threadlocal 中
        UserThreadLocal.put(sysUser);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserThreadLocal.remove();
    }
}
